TopicService = require('../service/TopicService')
errors = require('../errors')

exports.toCreateTopic = ->
    this.render('create-topic')

exports.gCreateTopic = ->
    userId = @state.userId

    this.checkBody('title').optional().notEmpty().len(2, 50, "标题长度在2-20位");
    yield return throw new errors.UserError(this.errors) if this.errors

    body = @request.body
    body.userId = userId
    r = yield from TopicService.gCreateTopic(body)
    this.body = r

exports.toTopicDetail = ->
    id = @params.id
    r = yield from TopicService.gGetTopicById(id)
    this.render('topic', {r})

exports.toEditTopic = ->
    id = @params.id
    r = yield from TopicService.gGetTopicById(id)
    this.render('create-topic', {r})

exports.gEditTopic = ->
    userId = @state.userId
    id = @params.id
    body = @request.body
    yield from TopicService.gEditTopic(id, body, userId)
    this.status = 204

exports.gDeleteTopic = ->
    userId = @state.userId
    id = @params.id
    yield from TopicService.gDeleteTopic(id, userId)
    this.status = 204
